
// In Chrome, you can view these log messages and many more useful pieces of
// debugging info at chrome://inspect/#service-workers
const CACHE_NAME = 'cboard-platform' + '__v1.0.0'
const cacheUrls = [
    './index.html',
    './cdn/vue/2.6.11/vue.min.js',
    './cdn/element-ui/2.13.0/index.min.js',
    './cdn/charts/echarts.min.4.8.0.js',
    './cdn/charts/echarts-wordcloud.min.js',
    './cdn/charts/echarts-liquidfill.min.js',
    './cdn/plugins/html2canvas.min.js',
    './cdn/plugins/jspdf.min.js',
]
self.addEventListener('install', function (e) {
    // This event will be fired once when this version of the script is first registered for
    // a given URL scope.
    // It's an opportunity to initialize caches and prefetch data, if desired. This sort of
    // work should be wrapped in a Promise, and e.waitUntil(promise) can be used to ensure that
    // this installation does not complete until the Promise is settled.
    // Also, be aware that there may already be an existing service worker controlling the page
    // (either an earlier version of this script or a completely different script.)
    console.log('Install event:', e);
    e.waitUntil(
        caches.open(CACHE_NAME).then(function(cache){
            return cache.addAll(cacheUrls)
        })
    )
});

self.addEventListener('activate', function (e) {
    // This event will be fired once when this version of the script is first registered for
    // a given URL scope.
    // It's an opportunity to clean up any stale data that might be left behind in self.caches
    // by an older version of this script.
    // e.waitUntil(promise) is also available here to delay activation until work has been performed,
    // but note that waiting within the activate event will delay handling of any
    // fetch or message events that are fired in the interim. When possible, do work during the install phase.
    // It will NOT be fired each time the service worker is revived after being terminated.
    // To perform an action when the service worker is revived, include that logic in the
    // `onfetch` or `onmessage` event listeners.
    console.log('Activate event:', e);
    e.waitUntil(
        caches.keys().then(function(keyList){
            return Promise.all(keyList.map(function(key){
                if(CACHE_NAME !== key) {
                    return caches.delete(key);
                }
            }))
        })
    )
});

self.addEventListener('fetch', function(event){
    event.respondWith(caches.match(event.request).then(function(resp) {
        if(resp) {
            return resp 
        } else {
            return fetch(event.request).then(function(response){
                const responseClone = response.clone();
                caches.open(CACHE_NAME).then(function(cache){
                    cache.put(event.request, responseClone)
                })
                return response
            })
        }
    }))
})
